package com.itheima.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.itheima.common.TokenHolder;
import com.itheima.domain.AddressBook;
import com.itheima.domain.OrderDetail;
import com.itheima.domain.Orders;
import com.itheima.domain.ShoppingCart;
import com.itheima.dto.OrdersDto;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.mapper.UserOrderDetailMapper;
import com.itheima.mapper.UserOrdersMapper;
import com.itheima.service.UserOrdersService;
import com.itheima.vo.UserOrdersVo;
import com.itheima.vo.UserTokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * @author CSY
 * 2022/5/14    14:52
 */
@Service
public class UserOrdersServiceImpl implements UserOrdersService {

    @Autowired
    private UserOrderDetailMapper userOrderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserOrdersMapper userOrdersMapper;

    /**
     * 添加订单信息
     *
     * @param orders
     * @return
     */
    @Transactional
    @Override
    public boolean addOrders(Orders orders) {
        String currentId = TokenHolder.getCurrentId();



        long id = new Snowflake().nextId();
        orders.setId(id);
        orders.setNumber(DigestUtils.md5DigestAsHex(LocalDateTime.now().toString().getBytes(StandardCharsets.UTF_8)));
        orders.setStatus(1);
        orders.setUserId(Long.valueOf(currentId));
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //TODO 从默认地址中获取收货人电话号码
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressInfo = userOrderDetailMapper.getAddressInfo(addressBookId);
        orders.setPhone(addressInfo.getPhone());
        //TODO 提交视为付款，状态变为待配送状态
        orders.setStatus(2);
        //TODO 从默认地址中获取收货人地址
        orders.setAddress(addressInfo.getDetail());
        //TODO 从默认地址中获取收货人
        orders.setConsignee(addressInfo.getConsignee());
        orders.setUserName(addressInfo.getConsignee());
        //TODO 获取订单的金额通过id值返回到这
        BigDecimal countAmount = shoppingCartMapper.getCountAmount(Long.valueOf(currentId));
        orders.setAmount(countAmount);

        int i = userOrdersMapper.AddressOrders(orders);

        //查询出购物车的信息，copy到订单明细中
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectShoppCartByUserId(Long.valueOf(currentId));
        int i1 =0;
        for (ShoppingCart shoppingCart : shoppingCarts) {

            OrderDetail orderDetail = new OrderDetail();
            BeanUtil.copyProperties(shoppingCart,orderDetail,"id");
            orderDetail.setId(new Snowflake().nextId());
            orderDetail.setOrderId(id);
            i1 = userOrderDetailMapper.addOrderDetail(orderDetail);
        }


        //支付完成
        if (i1>0){
            shoppingCartMapper.delect(Long.valueOf(currentId));
        }

        return i>0;
    }

    /**
     * 订单表分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Transactional
    @Override
    public UserOrdersVo getOrders(int page, int pageSize) {
        UserOrdersVo userOrdersVo = new UserOrdersVo();
        userOrdersVo.setCurrent(page);
        userOrdersVo.setSize(pageSize);
        //获取用户id,
        String currentId = TokenHolder.getCurrentId();
        page  = (page-1)*pageSize;
        List<Orders> orderses = userOrdersMapper.orderses(Long.valueOf(currentId), page, pageSize);

        List<OrdersDto> orderDetails =
                orderses.stream().filter(Objects::nonNull).map((res)->{
                    OrdersDto ordersDto = new OrdersDto();
                    BeanUtil.copyProperties(res,ordersDto);
                    Long id = res.getId();
                    List<OrderDetail> orderDetails1 = userOrderDetailMapper.orderDetails(id);
                    ordersDto.setOrderDetails(orderDetails1);
                    ordersDto.setOrderTime(res.getOrderTime());
                    ordersDto.setAmount(res.getAmount());
                    return ordersDto;
                }).collect(Collectors.toList());

        userOrdersVo.setRecords(orderDetails);

        int count = userOrdersMapper.count(Long.valueOf(currentId));
        userOrdersVo.setTotal(count);

        return userOrdersVo;
    } 
}
